<!DOCTYPE html>
<html lang="en">
  <head>
    <title>
        Java-framework-Spring-7-事务 - rulerLwx Blog
      </title>
        <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    
    <meta name="theme-color" content="#000000" />
    
    <meta http-equiv="window-target" content="_top" />
    
    
    <meta name="description" content="事务 基本概念 什么是事务？ 事务有很严格的定义，它必须同时满足4个条件：原子性（Atomicity）、一致性（Consistency）、隔离性（" />
    <meta name="generator" content="Hugo 0.73.0 with theme pure" />
    <title>Java-framework-Spring-7-事务 - rulerLwx Blog</title>
    
    
    <link rel="stylesheet" href="https://rulerLwx.gitee.io/css/style.min.c4bc7071f132c964c2116bca53b392933f377e5ca7b7051ed245187c621a2d3e.css">
    
    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/9.15.10/styles/github.min.css" async>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css" async>
    <meta property="og:title" content="Java-framework-Spring-7-事务" />
<meta property="og:description" content="事务 基本概念 什么是事务？ 事务有很严格的定义，它必须同时满足4个条件：原子性（Atomicity）、一致性（Consistency）、隔离性（" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://rulerLwx.gitee.io/2020/07/java-framework-spring-7-%E4%BA%8B%E5%8A%A1/" />
<meta property="article:published_time" content="2020-07-01T18:58:47+08:00" />
<meta property="article:modified_time" content="2020-07-01T18:58:47+08:00" />
<meta itemprop="name" content="Java-framework-Spring-7-事务">
<meta itemprop="description" content="事务 基本概念 什么是事务？ 事务有很严格的定义，它必须同时满足4个条件：原子性（Atomicity）、一致性（Consistency）、隔离性（">
<meta itemprop="datePublished" content="2020-07-01T18:58:47&#43;08:00" />
<meta itemprop="dateModified" content="2020-07-01T18:58:47&#43;08:00" />
<meta itemprop="wordCount" content="3192">



<meta itemprop="keywords" content="" /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Java-framework-Spring-7-事务"/>
<meta name="twitter:description" content="事务 基本概念 什么是事务？ 事务有很严格的定义，它必须同时满足4个条件：原子性（Atomicity）、一致性（Consistency）、隔离性（"/>

    <!--[if lte IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
      <![endif]-->

    <!--[if lt IE 9]>
        <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
      <![endif]-->
  </head>

  
  

  <body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader">
    <div class="slimContent">
      <div class="navbar-header">
        <div class="profile-block text-center">
          <a id="avatar" href="https://gitee.com/rulerLwx" target="_blank">
            <img class="img-circle img-rotate" src="https://rulerLwx.gitee.io/avatar.png" width="200" height="200">
          </a>
          <h2 id="name" class="hidden-xs hidden-sm">rulerLwx</h2>
          <h3 id="title" class="hidden-xs hidden-sm hidden-md">thinking...</h3>
          <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i>Guangzhou, China</small>
        </div><div class="search" id="search-form-wrap">
    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i
                        class="icon icon-search"></i></button>
            </span>
        </div>
        <div class="ins-search">
            <div class="ins-search-mask"></div>
            <div class="ins-search-container">
                <div class="ins-input-wrapper">
                    <input type="text" class="ins-search-input" placeholder="Type something..."
                        x-webkit-speech />
                    <button type="button" class="close ins-close ins-selectable" data-dismiss="modal"
                        aria-label="Close"><span aria-hidden="true">×</span></button>
                </div>
                <div class="ins-section-wrapper">
                    <div class="ins-section-container"></div>
                </div>
            </div>
        </div>
    </form>
</div>
        <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
        <ul class="nav navbar-nav main-nav">
            <li class="menu-item menu-item-home">
                <a href="/">
                    <i class="icon icon-home-fill"></i>
                  <span class="menu-title">Home</span>
                </a>
            </li>
            <li class="menu-item menu-item-archives">
                <a href="/posts/">
                    <i class="icon icon-archives-fill"></i>
                  <span class="menu-title">Archives</span>
                </a>
            </li>
            <li class="menu-item menu-item-categories">
                <a href="/categories/">
                    <i class="icon icon-folder"></i>
                  <span class="menu-title">Categories</span>
                </a>
            </li>
            <li class="menu-item menu-item-tags">
                <a href="/tags/">
                    <i class="icon icon-tags"></i>
                  <span class="menu-title">Tags</span>
                </a>
            </li>
            <li class="menu-item menu-item-about">
                <a href="/about/">
                    <i class="icon icon-cup-fill"></i>
                  <span class="menu-title">About</span>
                </a>
            </li>
        </ul>
      </nav>
    </div>
  </header>

<aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">enjoy~
            </div>
        </div>
    </div>
</div>

      <div class="widget">
    <h3 class="widget-title"> Categories</h3>
    <div class="widget-body">
        <ul class="category-list">
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-framework/" class="category-list-link">java-framework</a><span class="category-list-count">38</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-front-end/" class="category-list-link">java-front-end</a><span class="category-list-count">11</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-se/" class="category-list-link">java-se</a><span class="category-list-count">21</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-senior/" class="category-list-link">java-senior</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/linux/" class="category-list-link">linux</a><span class="category-list-count">13</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/tools/" class="category-list-link">tools</a><span class="category-list-count">1</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%8A%80%E6%9C%AF%E6%9D%82%E7%83%A9/" class="category-list-link">技术杂烩</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="category-list-link">数据库</a><span class="category-list-count">15</span></li>
        </ul>
    </div>
</div>
      <div class="widget">
    <h3 class="widget-title"> Tags</h3>
    <div class="widget-body">
        <ul class="tag-list">
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/jvm/" class="tag-list-link">jvm</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="tag-list-link">多线程</a><span
                    class="tag-list-count">2</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" class="tag-list-link">网络编程</a><span
                    class="tag-list-count">3</span></li>
            
        </ul>

    </div>
</div>
      
<div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
        <ul class="recent-post-list list-unstyled no-thumbnail">
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%87%AA%E5%B7%B1%E5%8A%A8%E6%89%8B%E4%B8%80%E6%89%B9%E9%87%8F%E7%A7%BB%E5%8A%A8%E9%87%8D%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6/" class="title">自己动手（一）——批量移动、重命名文件</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-27 17:50:02 &#43;0800 CST" itemprop="datePublished">2020-07-27</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E5%85%B3%E4%BA%8Einteger%E7%9A%84-128~127%E7%BC%93%E5%AD%98/" class="title">关于Integer的 -128~127缓存</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-11 16:56:21 &#43;0800 CST" itemprop="datePublished">2020-07-11</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" class="title">跨域问题</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-08 22:41:12 &#43;0800 CST" itemprop="datePublished">2020-07-08</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA/" class="title">个人博客搭建</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-05 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-05</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/centos/" class="title">CentOS-</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-01 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-01</time>
                    </p>
                </div>
            </li>
        </ul>
    </div>
</div>
  </div>
</aside>

    
    
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <h4 class="toc-title">Catalogue</h4>
    <nav id="toc" class="js-toc toc">

    </nav>
  </div>
</aside>
<main class="main" role="main"><div class="content">
  <article id="-" class="article article-type-" itemscope
    itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      <h1 itemprop="name">
  <a
    class="article-title"
    href="/2020/07/java-framework-spring-7-%E4%BA%8B%E5%8A%A1/"
    >Java-framework-Spring-7-事务</a
  >
</h1>

      <div class="article-meta">
        
<span class="article-date">
  <i class="icon icon-calendar-check"></i>&nbsp;
<a href="https://rulerLwx.gitee.io/2020/07/java-framework-spring-7-%E4%BA%8B%E5%8A%A1/" class="article-date">
  <time datetime="2020-07-01 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-01</time>
</a>
</span>
<span class="article-category">
  <i class="icon icon-folder"></i>&nbsp;
  <a class="article-category-link" href="/categories/java-framework/"> Java-framework </a>
</span>

        <span class="post-comment"><i class="icon icon-comment"></i>&nbsp;<a href="/2020/07/java-framework-spring-7-%E4%BA%8B%E5%8A%A1/#comments"
            class="article-comment-link">Comments</a></span>
		<span class="post-wordcount hidden-xs" itemprop="wordCount">Word Count: 3192words</span>
		<span class="post-readcount hidden-xs" itemprop="timeRequired">Read Count: 7minutes </span>
      </div>
    </div>
    <div class="article-entry marked-body js-toc-content" itemprop="articleBody">
      <h1 id="事务">事务</h1>
<h2 id="基本概念">基本概念</h2>
<p>什么是事务？</p>
<p>事务有很严格的定义，它必须同时满足4个条件：原子性（Atomicity）、一致性（Consistency）、隔离性（Isolation）、持久性（Durability）。</p>
<ul>
<li>原子性：指一个事务必须被视为一个不可分割的最小工作单元（要么全做，要么全不做）。</li>
<li>一致性：指事务将数据库从一种状态转变为下一种一致的状态。如违反唯一性约束时（即操作失败），系统自动撤销事务，返回初始化的状态。</li>
<li>隔离性：还可称为并发控制、可串行人、锁等，当多个用户并发访问数据库时，数据库为每个用户开启的事务，不能被其它事务的操作数据所干扰。</li>
<li>持久性：事务一旦提交，其所做的修改就会永久保存到数据库中。</li>
</ul>
<p>声明式事务基于Spring AOP实现。</p>
<p>Java EE应用的传统事务有两种策略：全局事务和局部事务。
全局事务由应用服务器管理，需要底层服务器的JTA支持。</p>
<p>Spring事务策略是通过PlatformTransactionManager接口体现的，系统只要使用不同的PlatformTransactionManager实现类即可。</p>
<p>即使使用容器管理的JTA，代码也依然无须执行JNDI查找，无须与特定的JTA资源耦合在一起，通过配置文件，JTA资源传给PlatformTransactionManager的实现类。因此，程序的代码可在JTA事务管理和非JTA事务管理之间轻松切换。</p>
<p>换句话说，Spring既支持全局事务，也支持局部事务，就看应用的底层是否支持了。</p>
<p>PlatformTransactionManager接口有如下方法：</p>
<ul>
<li>public void rollback(TransactionStatus arg0) throws TransactionException</li>
<li>public TransactionStatus getTransaction(TransactionDefinition arg0)</li>
<li>public void commit(TransactionStatus arg0) throws TransactionException</li>
</ul>
<p>TransactionDefinition接口定义了一个事务规则，该接口必须指定如下几个属性值：</p>
<ul>
<li>事务隔离：当前事务与其它事务的隔离程序。</li>
<li>事务传播：如果一个事务上下文已经存在，有几个选项可指定该事务性方法的执行行为。</li>
<li>事务超时：事务的最长持续时间。</li>
<li>只读状态：只读事务不修改任务数据。在某些情况下，只读事务是非常有用的优化。</li>
</ul>
<p>不同的PlatformTransactionManager的实现类：</p>
<p>1）JDBC：org.springframework.jdbc.datasource.DataSourceTransactionManager</p>
<p>2）JTA：org.springframework.transaction.jta.JtaTransactionManager （分布式事务）</p>
<p>3）Hibernate：org.springframework.orm.hibernate4.HibernateTransactionManager</p>
<p>4）JPA：JpaTransactionManager</p>
<p>5）JDO：JdoTransactionManager —— 《SpringBoot实战》汪云飞，p298</p>
<p>Spring提供如下两种事务管理方式：</p>
<p>1）编程式事务管理：即使使用Spring的编程式事务，程序也可直接获取容器中的transactionManager Bean，该Bean总是PlatformTransactionManager的实例，所以可能通过该接口提供的三个方法来开始事务，提交事务和回滚事务。
（通过TransactionTemplate类操作事务更简捷）</p>
<p>2）声明式事务管理：分为XML配置方式、Annotation注解方式。</p>
<h2 id="xml配置事务">XML配置事务</h2>
<p>1、引入tx:命名空间：</p>
<pre><code>xmlns:tx=&quot;http://www.springframework.org/schema/tx&quot;
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
</code></pre>
<p>2、<a href="tx:advice.../">tx:advice.../</a>元素除了需要transaction-manager属性指定事务管理器之外，还需要一个<a href="tx:attributes.../">tx:attributes.../</a>子元素，该子元素又可包含多个<a href="tx:method.../">tx:method.../</a>子元素。</p>
<p><a href="tx:method.../">tx:method.../</a>子元素可配置如下几个属性：</p>
<ul>
<li>name：指定对哪些方法起作用。</li>
<li>propagation：事务传播属性。</li>
<li>isolation：事务隔离属性。</li>
<li>timeout：事务超时属性。</li>
<li>read-only：只读属性。</li>
<li>rollback-for：对指定异常回滚。</li>
<li>no-rollback-for：对指定异常不回滚。</li>
</ul>
<p>其中propagation的事务传播行为有如下几种：</p>
<ul>
<li>MANDATORY：要求调用该方法的线程必须处于事务环境中，否则抛异常。</li>
<li>NESTED：即使执行该方法的线程已牌事务环境中，也依然启动新的事务，方法嵌套在事务里执行。</li>
<li>NEVER：不允许调用该方法的线程处于事务环境中，否则抛异常。</li>
<li>NOT_SUPPORTED：如果调用该方法的线程处于事务环境中，则先暂停当前事务，然后执行该方法。</li>
<li>REQUIRED：要求在事务环境中执行该方法。如果当前执行线程已处于事务环境中，则直接调用；如果当前执行线程不处于事务环境中，则启动新的事务后执行该方法。</li>
<li>REQUIRES_NEW：要求在新的事务环境中执行。如果当前执行线程已经处于事务环境中，则先暂停当前事务，启动新事务后执行该方法；如果当前调用线程不处于事务环境中，则启动新的事务后执行该方法。</li>
<li>SUPPORTS：如果当前执行线程处于事务环境中，则使用当前事务，否则不使用事务。</li>
</ul>
<p>示例：</p>
<pre><code>public class NewsDaoImpl implements NewsDao{
	private DataSource ds;
	public void setDs(DataSource ds){
		this.ds = ds;
	}
	public void insert(String title, String content){
		JdbcTemplate jt = new JdbcTemplate(ds);
		jt.update(&quot;insert into news_inf&quot;+ &quot; values(null , ? , ?)&quot;, title , content);
		// 两次插入的数据违反唯一键约束
		jt.update(&quot;insert into news_inf&quot;+ &quot; values(null , ? , ?)&quot;, title , content);
		// 如果没有事务控制，则第一条记录可以被插入
		// 如果增加事务控制，将发现第一条记录也插不进去。
	}
}
</code></pre>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;GBK&quot;?&gt;
&lt;beans xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:p=&quot;http://www.springframework.org/schema/p&quot;
	xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;
	xmlns:tx=&quot;http://www.springframework.org/schema/tx&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx-4.0.xsd&quot;&gt;

	&lt;bean id=&quot;dataSource&quot; class=&quot;com.mchange.v2.c3p0.ComboPooledDataSource&quot;
		destroy-method=&quot;close&quot;
		p:driverClass=&quot;com.mysql.jdbc.Driver&quot;
		p:jdbcUrl=&quot;jdbc:mysql://localhost/spring&quot;
		p:user=&quot;root&quot;
		p:password=&quot;32147&quot;
		p:maxPoolSize=&quot;40&quot;
		p:minPoolSize=&quot;2&quot;
		p:initialPoolSize=&quot;2&quot;
		p:maxIdleTime=&quot;30&quot;/&gt;

	&lt;bean id=&quot;transactionManager&quot; 
		class=&quot;org.springframework.jdbc.datasource.DataSourceTransactionManager&quot;
		p:dataSource-ref=&quot;dataSource&quot;/&gt;

	&lt;bean id=&quot;newsDao&quot; class=&quot;org.crazyit.app.dao.impl.NewsDaoImpl&quot; p:ds-ref=&quot;dataSource&quot;/&gt;

	&lt;tx:advice id=&quot;txAdvice&quot; transaction-manager=&quot;transactionManager&quot;&gt;
		&lt;tx:attributes&gt;
			&lt;tx:method name=&quot;get*&quot; read-only=&quot;true&quot;/&gt;
			&lt;tx:method name=&quot;*&quot; isolation=&quot;DEFAULT&quot; propagation=&quot;REQUIRED&quot; timeout=&quot;5&quot;/&gt;
		&lt;/tx:attributes&gt;
	&lt;/tx:advice&gt;

	&lt;aop:config&gt;
		&lt;aop:pointcut id=&quot;myPointcut&quot; expression=&quot;execution(* org.crazyit.app.dao.impl.*Impl.*(..))&quot;/&gt;
		&lt;aop:advisor advice-ref=&quot;txAdvice&quot; pointcut-ref=&quot;myPointcut&quot;/&gt;
	&lt;/aop:config&gt;
&lt;/beans&gt;
</code></pre>
<p>总结：事务中的切面类是Spring定义好了的（以前都是咱自己用@Aspect定义的）。</p>
<h2 id="annotation配置事务">Annotation配置事务</h2>
<p>@Transactional注解，可用于类（对类下的所有方法有效）、方法上。</p>
<p>使用@Transactional时，可指定如下属性：</p>
<ul>
<li>isolation：指定事务隔离级别。默认为底层事务的隔离级别。</li>
<li>noRollbackFor()：指定遇到特定异常时强制不回滚事务。</li>
<li>noRollbackForClassName()：指定遇到特定的多个异常时强制不回滚事务。该属性可以指定多个异常类名。</li>
<li>propagation()：指定事务传播行为。</li>
<li>readOnly：指定事务是否只读。</li>
<li>rollbackFor()：定遇到特定异常时强制回滚事务。</li>
<li>rollbackForClassName()：指定遇到特定的多个异常时强制回滚事务。该属性可以指定多个异常类名。</li>
<li>timeout()：指定事务的超时时长。</li>
</ul>
<p>总结：看源码，就知道要配置的值是哪些东西了。</p>
<p>配置步骤：</p>
<p>1）在需要使用事务的类或方法上使用@Transactional注解</p>
<p>2）在beans.xml文件中增加两个配置：</p>
<pre><code>&lt;bean class=&quot;org.springframework.jdbc.datasource.DataSourceTransactionManager&quot; 
	id=&quot;transactionManager&quot; p:dataSource-ref=&quot;dataSource&quot;/&gt;
&lt;tx:annotation-driven transaction-manager=&quot;transactionManager&quot;/&gt;
</code></pre>
<p>示例：</p>
<pre><code>public interface NewsDao {
	public void insert(String title, String content);
}
</code></pre>
<pre><code>public class NewsDaoImpl implements NewsDao {
	private DataSource ds;
	public void setDs(DataSource ds){
		this.ds = ds;
	}
	
	@Transactional(propagation=Propagation.REQUIRED ,isolation=Isolation.DEFAULT , timeout=5)
	public void insert(String title, String content){
		JdbcTemplate jt = new JdbcTemplate(ds);
		jt.update(&quot;insert into news_inf&quot;+ &quot; values(null , ? , ?)&quot;, title , content);
		// 两次插入的数据违反唯一键约束
		jt.update(&quot;insert into news_inf&quot;+ &quot; values(null , ? , ?)&quot;, title , content);
		// 如果没有事务控制，则第一条记录可以被插入
		// 如果增加事务控制，将发现第一条记录也插不进去。
	}
}
</code></pre>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;GBK&quot;?&gt;
&lt;beans xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:p=&quot;http://www.springframework.org/schema/p&quot;
	xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;
	xmlns:tx=&quot;http://www.springframework.org/schema/tx&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx-4.0.xsd&quot;&gt;

	&lt;bean id=&quot;dataSource&quot; class=&quot;com.mchange.v2.c3p0.ComboPooledDataSource&quot;
		destroy-method=&quot;close&quot;
		p:driverClass=&quot;com.mysql.jdbc.Driver&quot;
		p:jdbcUrl=&quot;jdbc:mysql://localhost/spring&quot;
		p:user=&quot;root&quot;
		p:password=&quot;32147&quot;
		p:maxPoolSize=&quot;40&quot;
		p:minPoolSize=&quot;2&quot;
		p:initialPoolSize=&quot;2&quot;
		p:maxIdleTime=&quot;30&quot;/&gt;

	&lt;bean id=&quot;newsDao&quot; class=&quot;org.crazyit.app.dao.impl.NewsDaoImpl&quot; p:ds-ref=&quot;dataSource&quot;/&gt;

	&lt;bean id=&quot;transactionManager&quot; 
		class=&quot;org.springframework.jdbc.datasource.DataSourceTransactionManager&quot;
		p:dataSource-ref=&quot;dataSource&quot;/&gt;
		
	&lt;tx:annotation-driven transaction-manager=&quot;transactionManager&quot;/&gt;

&lt;/beans&gt;
</code></pre>
<pre><code>public class SpringTest{
	public static void main(String[] args){
		ApplicationContext ctx = new ClassPathXmlApplicationContext(&quot;beans.xml&quot;);
		NewsDao dao = (NewsDao)ctx.getBean(&quot;newsDao&quot; , NewsDao.class);
		dao.insert(&quot;疯狂Java&quot; , &quot;轻量级Java EE企业应用实战&quot;);
	}
}
</code></pre>
<h1 id="faq">FAQ</h1>
<h2 id="只读事务-transactionalreadonly--true">只读事务 @Transactional(readOnly = true)</h2>
<p>如果你一次执行单条查询语句，则没有必要启用事务支持，数据库默认支持SQL执行期间的读一致性；</p>
<p>如果你一次执行多条查询语句，例如统计查询，报表查询，在这种场景下，多条查询SQL必须保证整体的读一致性，否则，在前条SQL查询之后，后条SQL查询之前，数据被其他用户改变，则该次整体的统计查询将会出现读数据不一致的状态，此时，应该启用事务支持。</p>
<p>参考：https://blog.csdn.net/xingqibaing/article/details/82838146</p>

    </div>
    <div class="article-footer">
<blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-link hidden-xs">
      <strong>Permalink: </strong>
      <a href="https://rulerLwx.gitee.io/2020/07/java-framework-spring-7-%E4%BA%8B%E5%8A%A1/" title="Java-framework-Spring-7-事务" target="_blank" rel="external">https://rulerLwx.gitee.io/2020/07/java-framework-spring-7-%E4%BA%8B%E5%8A%A1/</a>
    </li>
    <li class="post-copyright-license">
      <strong>License：</strong><a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN</a>
    </li>
  </ul>
</blockquote>

<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/rulerLwx" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://rulerLwx.gitee.io/avatar.png" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/rulerLwx" target="_blank"><span class="text-dark">rulerLwx</span><small class="ml-1x">thinking...</small></a></h3>
        <div>Good Good Study, Day Day Up~</div>
      </div>
    </figure>
  </div>
</div>
    </div>
  </article>
<section id="comments">
    <div id="vcomments"></div>
</section>

</div><nav class="bar bar-footer clearfix" data-stick-bottom>
    <div class="bar-inner">
        <ul class="pager pull-left">
            <li class="prev">
                <a href="https://rulerLwx.gitee.io/2020/07/java-framework-spring-8/" title="Java-framework-Spring-8"><i
                        class="icon icon-angle-left"
                        aria-hidden="true"></i><span>&nbsp;&nbsp;Older</span></a>
            </li>
            <li class="next">
                <a href="https://rulerLwx.gitee.io/2020/07/java-framework-spring-6-aop/"
                    title="Java-framework-Spring-6-AOP"><span>Newer&nbsp;&nbsp;</span><i
                        class="icon icon-angle-right" aria-hidden="true"></i></a>
            </li>
            
            <li class="toggle-toc">
                <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false"
                    title="Catalogue" role="button">
                    <span>[&nbsp;</span><span>Catalogue</span>
                    <i class="text-collapsed icon icon-anchor"></i>
                    <i class="text-in icon icon-close"></i>
                    <span>]</span>
                </a>
            </li>
        </ul>
        <div class="bar-right">
            <div class="share-component" data-sites="weibo,qq,wechat"
                data-mobile-sites="weibo,qq,qzone"></div>
        </div>
    </div>
</nav>

</main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
<ul class="social-links">
    <li><a href="https://gitee.com/rulerLwx" target="_blank" title="gitee" data-toggle=tooltip data-placement=top >
            <i class="icon icon-gitee"></i></a></li>
    <li><a href="https://github.com/wolf-lea" target="_blank" title="github" data-toggle=tooltip data-placement=top >
            <i class="icon icon-github"></i></a></li>
</ul>
  <div class="copyright">
    &copy;2020  -
    2020
    <div class="publishby">
        Theme by <a href="https://github.com/xiaoheiAh" target="_blank"> xiaoheiAh </a>base on<a href="https://github.com/xiaoheiAh/hugo-theme-pure" target="_blank"> pure</a>.
    </div>
  </div>
</footer>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_SVG"></script>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
            showMathMenu: false, //disables context menu
            tex2jax: {
            inlineMath: [ ['$','$'], ['\\(','\\)'] ]
           }
    });
</script>


<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/highlight.min.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/python.min.js" defer></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/javascript.min.js" defer></script><script>
    hljs.configure({
        tabReplace: '    ', 
        classPrefix: ''     
        
    })
    hljs.initHighlightingOnLoad();
</script>
<script src="https://rulerLwx.gitee.io/js/application.min.bdeb64b910570b6c41badc6a05b7afb0c8ad9efd8525de3c7257d59e786326a3.js"></script>
<script src="https://rulerLwx.gitee.io/js/plugin.min.51ff8c7317566f82259170fa36e09c4493adc9b9378b427a01ad3f017ebac7dd.js"></script>

<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: 'Posts',
                PAGES: 'Pages',
                CATEGORIES: 'Categories',
                TAGS: 'Tags',
                UNTITLED: '(Untitled)',
            },
            ROOT_URL: 'https:\/\/rulerLwx.gitee.io',
            CONTENT_URL: 'https:\/\/rulerLwx.gitee.io\/searchindex.json ',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script type="text/javascript" src="https://rulerLwx.gitee.io/js/insight.min.a343cd9a5a7698336b28ef3a7c16a3a1b1d2d5fb17dc8ed04022bbe08cc5459073a15bdafa3a8a58cdd56080784bdd69fa70b1ae8597565c799c57ed00f0e120.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script>
<script>
    tocbot.init({
        
        tocSelector: '.js-toc',
        
        contentSelector: '.js-toc-content',
        
        headingSelector: 'h1, h2, h3',
        
        hasInnerContainers: true,
    });
</script>

<script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine"></script>
<script type="text/javascript">
    var GUEST = ['nick', 'mail', 'link'];
    var meta = 'nick,mail';
    meta = meta.split(',').filter(function (item) {
        return GUEST.indexOf(item) > -1;
    });
    new Valine({
        el: '#vcomments',
        verify: null ,
        notify: null ,
        appId: 'IyAB0PSPRazTPDxitO1ddQ7O-gzGzoHsz',
        appKey: '5rBJTq4KidYF33eXwvRVhtEH',
        placeholder: 'enjoy~',
        avatar: 'mm',
        meta: meta,
        pageSize: '10' || 10,
        visitor: false 
});
</script>

  </body>
</html>
